package com.natalia.excel.service.impl;

import com.natalia.excel.service.DownloadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

/**
 * @Author yang
 **/
@Slf4j
@Service
public class DownloadServiceImpl implements DownloadService {

    /**
     * 导出word文档
     * @return
     */
    @Override
    public XWPFDocument getWordXWPFDocument() {
        //文本对象
        XWPFDocument doc = new XWPFDocument();
        //创建段落
        XWPFParagraph paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun run = paragraph.createRun();
        run.setText("paragraph test");
        setParagraphSpacing(paragraph,0,10,1);
        return doc;
    }

    /**
     * 调整段落间距【对应word段落设置-间距设置】
     *
     * @param before   段前  几倍行距
     * @param after    段后  几倍行距
     * @param multiple 几倍行距
     */
    public static void setParagraphSpacing(XWPFParagraph paragraph, float before, float after, float multiple) {
        CTPPr ppr = paragraph.getCTP().getPPr();
        if (ppr == null) {
            ppr = paragraph.getCTP().addNewPPr();
        }
        CTSpacing spacing = ppr.isSetSpacing() ? ppr.getSpacing() : ppr.addNewSpacing();
        spacing.setBefore(BigInteger.valueOf(Math.round(before * 240)));
        spacing.setAfter(BigInteger.valueOf(Math.round(after * 240)));
        spacing.setLine(BigInteger.valueOf(Math.round(240 * multiple)));
        spacing.setLineRule(STLineSpacingRule.AUTO);
    }
}
